package com.hmall.order.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hmall.common.dto.OrderDetail;
import com.hmall.common.pojo.Order;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.pojo.OrderDto;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("order")
public class OrderController {

   @Autowired
   private IOrderService orderService;

   @Autowired
   private OrderDetailMapper orderDetailMapper;

   @GetMapping("/{id}")
   public Order queryOrderById(@PathVariable("id") Long orderId) {
      return orderService.getById(orderId);
   }

   /**
    * 查询超时订单的详细订单信息
    * @param orderId
    * @return
    */
   @GetMapping
   public List<OrderDetail> queryOrderDetailById(@RequestParam("orderId") Long orderId) {
      LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(OrderDetail::getOrderId, orderId);
      return orderDetailMapper.selectList(wrapper);
   }

   /**
    * 提交订单
    * @return
    */
   @PostMapping
   public String submit(@RequestBody OrderDto orderDto){
      Long orderId = orderService.submit(orderDto);
      return orderId+"";
   }

   @GetMapping("/list")
   public List<Order> selectList(){
      LocalDateTime now = LocalDateTime.now();
      LocalDateTime nowMinus30 = now.plusMinutes(-30);

      LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(Order::getStatus, "1");
      wrapper.lt(Order::getCreateTime, nowMinus30);

      return orderService.list(wrapper);
   }

   /**
    * 根据id更新订单
    * @param orderId
    */
   @PutMapping
   public void updateOrder(Long orderId){

      if(orderId!=null){

         LambdaUpdateWrapper<Order> wrapper = new LambdaUpdateWrapper<>();
         wrapper.set(Order::getStatus, 5);
         wrapper.eq(Order::getId, orderId);

         orderService.update(wrapper);
      }

   }
}
